<template>
  <el-scrollbar :max-height="vueData.maxHeight">
    <el-form ref="masterFormRef" :label-width="vueData.labelWidth" :model="vueData.formData">
      <el-row class="field-row">
        <el-col class="field-col" :span="vueData.fieldSpan" v-for="item in vueData.fieldList">
          <el-form-item
            class="field-item"
            v-if="item.dataType === dataType.STR.val"
            :label="item.name"
            :prop="item.hideCode"
            :rules="item.rules"
          >
            <el-input
              v-model="vueData.formData[item.hideCode]"
              :maxlength="item.ext.maxLen || 100"
              style="width: 80%"
            />
            <el-popover
              placement="bottom"
              :title="item.name"
              :width="200"
              trigger="click"
              content="提示"
            >
              <template #reference>
                <el-button class="m-2" icon="Warning"/>
              </template>
            </el-popover>
          </el-form-item>
          <el-form-item
            class="field-item"
            v-if="item.dataType === dataType.NUM.val"
            :label="item.name"
            :prop="item.hideCode"
            :rules="item.rules"
          >
            <el-input-number
              v-model="vueData.formData[item.hideCode]"
              :min="item.ext.minNum || -99999999999999"
              :max="item.ext.maxNum || 99999999999999"
              :controls="false"
              :precision="item.ext.decLen"
            />
            <el-popover
              placement="bottom"
              :title="item.name"
              :width="200"
              trigger="click"
              content="提示"
            >
              <template #reference>
                <el-button class="m-2" icon="Warning"/>
              </template>
            </el-popover>
          </el-form-item>
          <el-form-item
            class="field-item"
            v-if="item.dataType === dataType.DATE.val"
            :label="item.name"
            :prop="item.hideCode"
            :rules="item.rules"
          >
            <el-date-picker
              v-model="vueData.formData[item.hideCode]"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="() => { return true; }"
            />
            <el-popover
              placement="bottom"
              :title="item.name"
              :width="200"
              trigger="click"
              content="提示"
            >
              <template #reference>
                <el-button class="m-2" icon="Warning"/>
              </template>
            </el-popover>
          </el-form-item>
          <el-form-item
            class="field-item"
            v-if="item.dataType === dataType.FILE.val"
            :label="item.name"
            :prop="item.hideCode"
          >
            <el-input v-model="vueData.formData[item.hideCode]" :maxlength="item.ext.maxLen || 100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-scrollbar>
</template>

<script name="CodeEditor" setup>
import { getCurrentInstance, reactive, watchEffect } from 'vue';
import PropEnum from '@/store/enums/PropEnum';
import { SwitchEnum } from '@/store/enums/SwitchEnum';
import applyApi from '@/api/data/apply.js';

const { proxy } = getCurrentInstance();
const { dataType } = PropEnum;

const props = defineProps({
  modelInfo: {
    required: true,
    type: Object,
  },
});

const vueData = reactive({
  maxHeight: 600,
  labelWidth: 140,
  fieldSpan: 12,
  fieldList: [],
  formData: {},
  actionType: 0,
  baseData: {
    uid: null,
    revision: null,
  },
});

function loadPropList(propList) {
  vueData.fieldList = [];
  propList.forEach(it => {
    if (it.viewType !== 'X2') {
      const ft = { ...it };
      ft.rules = [];
      if (it.ext.notNvl === SwitchEnum.OPEN) {
        ft.rules.push({
          required: true,
          message: `${it.name}不能为空`,
          trigger: 'blur',
        });
      }
      vueData.fieldList.push(ft);
    }
  });
}

/**
 * 新增时，加载默认值
 * 编辑时，获取原值
 */
function loadEditorData(rec) {
  proxy.$refs.masterFormRef.clearValidate();
  if (rec?.uid != null && rec?.uid !== '') {
    console.log(rec.uid);
    vueData.baseData.uid = rec.uid;
    vueData.baseData.revision = rec.revision;
  }
}

function handleSave() {
  vueData.actionType = 0;
  validAndSave();
}

function handleSubmit() {
  vueData.actionType = 1;
  validAndSave();
}

function validAndSave() {
  const formRef = proxy.$refs.masterFormRef;
  formRef.validate((valid, fields) => {
    if (valid) {
      const { code, areaCode } = props.modelInfo;
      const params = {
        areaCode: areaCode,
        modelCode: code,
        typeSrc: '0', // 界面添加
        ...vueData.baseData,
        actionType: vueData.actionType,
        dataList: [],
      };
      vueData.fieldList.forEach(it => {
        params.dataList.push({
          hc: it.hideCode,
          sv: vueData.formData[`${it.hideCode}Name`],
          vv: vueData.formData[it.hideCode],
        });
      });
      applyApi.saveData(params, areaCode).then(res => {
        if (res.code === 200) {
          vueData.baseData.uid = res.data.uid;
          vueData.baseData.revision = res.data.revision;
          proxy.$modal.msgSuccess("操作成功");
        } else {
          proxy.$modal.msgSuccess(`操作失败:${res.msg}`);
        }
      }).catch(() => {
        proxy.$modal.msgSuccess("操作失败: 后台错误");
      });
    } else {
      formRef.scrollToField(fields[0]);
    }
  });
}

watchEffect(() => {
  if (props.modelInfo != null && props.modelInfo.propList) {
    let propList = props.modelInfo.propList;
    loadPropList(propList);
  }
});

defineExpose({
  loadEditorData,
  handleSave,
  handleSubmit,
});
</script>

<style lang='scss' scoped>
.me-code-editor {
  min-width: 150px;
  width: 20%;
}
</style>